package com.edou.base.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.edou.base.util.ZXingUtils;

/**
 * 二维码
 */
@Controller("qRCodeController")
@Scope("prototype")
@RequestMapping(value = "/qrcode")
public class QRCodeController extends BaseController{
	 
	@Value("${qrcode.logo.path}")
	private String logoPath;
	 /**
	 * 生成二维码
	 * 1、content为二维码跳转链接
	 * 2、如果content中有#字符，则需要传递的链接中将其改为其他字符
	 * 3、并且传递replace参数为改替后的字符
	 * 4、后台接收会对content中包含的replace进行统一替换为#
	 * @return
	 */
	@RequestMapping(value = "/generate.htm",  method = {RequestMethod.GET,RequestMethod.POST})
	public void generate(HttpServletRequest request,HttpServletResponse response)throws Exception{
		//跳转链接
		String content = request.getParameter("content");
		ServletOutputStream out = response.getOutputStream();
		if(StringUtils.isBlank(content)){
			content = "未配置跳转链接";
		}
		//为了解决该字段#会被过滤问题，则获取替换字段进行还原#号
		String replace = request.getParameter("replace");
		if(StringUtils.isNotBlank(replace)){
			content = content.replace(replace, "#");
		}
		if(StringUtils.isNotBlank(logoPath)){
			String srcImagePath = getRealPath(logoPath,request);
			BufferedImage im = ZXingUtils.genBarcode(content, 208, 208, srcImagePath);
			ImageIO.write(im, "JPEG", out);
		}else{
			BufferedImage im = ZXingUtils.genBarcode(content, 208, 208);
			ImageIO.write(im, "JPEG", out);
		}
	}
	
}
